﻿using Coldairarrow.Business.AOP;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.FP;
using Coldairarrow.Entity.PB;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.Helper;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_MobilizationNoticeBusiness : BaseBusiness<PB_MobilizationNotice>, IPB_MobilizationNoticeBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        public PB_MobilizationNoticeBusiness(IDbAccessor db, IOperator @operator)
            : base(db)
        {
            _operator = @operator;
        }

        #region 外部接口

        public async Task<PageResult<PB_MobilizationNotice>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_MobilizationNotice>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_MobilizationNotice, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PB_MobilizationNoticeDto> GetTheDataAsync(string id)
        {
            Expression<Func<PB_MobilizationNotice, Base_OverFlow, PB_MobilizationNoticeDto>> select = (a, b) => new PB_MobilizationNoticeDto
            {
                WorkFlowName = b.Title,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_OverFlow>() on a.WorkFlow equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            //筛选
            q = q.Where(m=>m.Id==id);
            return await q.FirstOrDefaultAsync();
        }

        
        public async Task AddDataAsync(PB_MobilizationNotice data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(PB_MobilizationNotice data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
            foreach (var item in ids) {
                string sqlMain = @" Delete from PB_MobilzationItem  where ParentId in('" + item+ "') ";
                await ExecuteSqlAsync(sqlMain);
            }


        }

        /// <summary>
        /// 组装进场通知单数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task AddDataListInfo(PB_MobilizationNoticeSubDTO data)
        {
            string Abstract = "";
            var RellName =await Db.GetIQueryable<Base_User>().Where(m=>m.Id==_operator.UserId).FirstOrDefaultAsync();
            //创建进场通知单楼号集合
            List<PB_MobilzationItem> SubData = new List<PB_MobilzationItem>();
            //组装进场通知单主表数据
            PB_MobilizationNotice MainData = new PB_MobilizationNotice();
            //string id = IdHelper.GetId();
            MainData.Id = data.MaiData.Id;
            MainData.ProjectId = data.MaiData.ProjectId;
            MainData.ProjectName = data.MaiData.ProjectName;
            MainData.CooperativeUnitId = data.MaiData.CooperativeUnitId;
            MainData.CooperativeUnitName = data.MaiData.CooperativeUnitName;
            MainData.SaleUnitId = data.MaiData.SaleUnitId;
            MainData.SaleUnitName = data.MaiData.SaleUnitName;
            MainData.SignUnitId = data.MaiData.SignUnitId;
            MainData.SignUnitName = data.MaiData.SignUnitName;
            MainData.TypeId = data.MaiData.TypeId;
            MainData.ContractNo = data.MaiData.ContractNo;
            MainData.IssueDate = data.MaiData.IssueDate;
            MainData.AuditStatus = 0;
            MainData.Deleted = false;
            MainData.CreateTime = DateTime.Now;
            MainData.CreatorId = _operator.UserId;
            MainData.CreatorName = RellName.RealName;
            MainData.Remark = data.MaiData.Remark;
            MainData.WorkFlow = data.MaiData.WorkFlow;
            MainData.BusinessLeader = data.MaiData.BusinessLeader;
            MainData.DocumentaryContact = data.MaiData.DocumentaryContact;
            for (int i=0;i<data.SubData?.Count;i++) {
                string SubId = IdHelper.GetId();
                PB_MobilzationItem pB_MobilzationItem = new PB_MobilzationItem();
                pB_MobilzationItem.Id = SubId;//详情id;
                pB_MobilzationItem.CreateTime = DateTime.Now;
                pB_MobilzationItem.CreatorId = _operator?.UserId; //创建人
                pB_MobilzationItem.CreatorName =RellName.RealName;
                pB_MobilzationItem.Deleted = false;
                pB_MobilzationItem.ParentId = data.MaiData.Id; //id;
                pB_MobilzationItem.Remarks = data.SubData?[i].Remarks;
                pB_MobilzationItem.BuildingnumberId = data.SubData?[i].BuildingnumberId;//楼号
                pB_MobilzationItem.ProductModel = data.SubData[i].ProductModel;//产品型号
                pB_MobilzationItem.MobilizationTime = data.SubData[i].MobilizationTime;//进场时间
                pB_MobilzationItem.BuildingNo = data.SubData?[i].BuildingNo;
                if (data.SubData?.Count == 1)
                {
                    Abstract += data.SubData?[i].BuildingNo;
                }
                else
                {
                    Abstract += data.SubData?[i].BuildingNo + ",";
                }
                SubData.Add(pB_MobilzationItem);
            }
            MainData.Abstract = data.MaiData.Abstract == null ? data.MaiData.ProjectName + ",楼号:[" + Abstract + "]" : data.MaiData.Abstract;
            await InsertAsync(MainData);
            await Db.InsertAsync<PB_MobilzationItem>(SubData);
        }

        /// <summary>
        /// 修改操作
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
      public async Task UpdateDataListInfo(PB_MobilizationNoticeSubDTO data)
        {
            string sqlMain = @" Delete from PB_MobilzationItem  where ParentId='" + data.MaiData.Id+ "' ";
            await ExecuteSqlAsync(sqlMain);
            var RellName = await Db.GetIQueryable<Base_User>().Where(m => m.Id == _operator.UserId).FirstOrDefaultAsync();
            List<string> ItemIdinfo = new List<string>();
            //编辑进场通知单楼号集合
            List<PB_MobilzationItem> SubData = new List<PB_MobilzationItem>();
            //组装进场通知单主表数据
            PB_MobilizationNotice MainData = new PB_MobilizationNotice();
            string id = IdHelper.GetId();
            MainData.Id = id;
            MainData.ProjectId = data.MaiData.ProjectId;
            MainData.ProjectName = data.MaiData.ProjectName;
            MainData.CooperativeUnitId = data.MaiData.CooperativeUnitId;
            MainData.CooperativeUnitName = data.MaiData.CooperativeUnitName;
            MainData.SaleUnitId = data.MaiData.SaleUnitId;
            MainData.SaleUnitName = data.MaiData.SaleUnitName;
            MainData.SignUnitId = data.MaiData.SignUnitId;
            MainData.SignUnitName = data.MaiData.SignUnitName;
            MainData.TypeId = data.MaiData.TypeId;
            MainData.ContractNo = data.MaiData.ContractNo;
            MainData.IssueDate = data.MaiData.IssueDate;
            MainData.AuditStatus = 0;
            MainData.Deleted = false;
            MainData.CreateTime = DateTime.Now;
            MainData.CreatorId = _operator.UserId;
            MainData.CreatorName =data.MaiData.CreatorName;
            MainData.Remark = data.MaiData.Remark;
            MainData.WorkFlow = data.MaiData.WorkFlow;
            MainData.BusinessLeader = data.MaiData.BusinessLeader;
            MainData.DocumentaryContact = data.MaiData.DocumentaryContact;
            for (int i = 0; i < data.SubData?.Count; i++) {
                PB_MobilzationItem PB_DeliveryNoticeItem = new PB_MobilzationItem();
                    PB_DeliveryNoticeItem.Id = IdHelper.GetId();
                    PB_DeliveryNoticeItem.CreateTime = DateTime.Now;//设计清单主表id
                    PB_DeliveryNoticeItem.CreatorId = _operator?.UserId; //创建人
                    PB_DeliveryNoticeItem.CreatorName = RellName.RealName;
                    PB_DeliveryNoticeItem.Deleted = false;//物料id
                    PB_DeliveryNoticeItem.ParentId = data.MaiData.Id;
                    PB_DeliveryNoticeItem.Remarks = data.SubData?[i].Remarks;
                PB_DeliveryNoticeItem.MobilizationTime = data.SubData?[i].MobilizationTime;
                PB_DeliveryNoticeItem.ProductModel = data.SubData?[i].ProductModel;
                    PB_DeliveryNoticeItem.BuildingnumberId = data.SubData?[i].BuildingnumberId;
                    PB_DeliveryNoticeItem.BuildingNo = data.SubData?[i].BuildingNo;
                SubData.Add(PB_DeliveryNoticeItem);
                }

            await Db.InsertAsync<PB_MobilzationItem>(SubData);
            
        }

        /// <summary>
        /// 审核进场通知单
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>

        [OverFlowBegin("MobilizationNotice")]
        public async Task ToExamineRepairOrderApply(string Id)
        {
            string sqlMain = @" update PB_MobilizationNotice set `AuditStatus`=1 where Id='" + Id + "' ";
            await ExecuteSqlAsync(sqlMain);
            //推送第一级
            List<string> ulist = new List<string>();
            //获取进场通知单数据
            StringBuilder sql = new StringBuilder();
            sql.Append("SELECT ");
            sql.Append("b.Id,");
            sql.Append("b.Content,");
            sql.Append("ifnull(c.LEVEL,0) LEVEL ");
            sql.Append("FROM ");
            sql.Append("PB_MobilizationNotice a ");
            sql.Append("LEFT JOIN Base_OverFlow b ON a.WorkFlow = b.Id ");
            sql.Append("LEFT JOIN Base_OverFlowTask c ON a.Id = c.BillId  ");
            sql.Append("WHERE ");
            sql.Append("a.Id = '" + Id + "'");
            Util.Helper.DingInputDTO input = new Util.Helper.DingInputDTO();
            string uids = "";
            var flowMob = await Db.GetListBySqlAsync<CurrentOverFlowDTO>(sql.ToString());
            JArray farrMob = JArray.Parse(flowMob[0].Content);
            JObject _objMob = JObject.Parse(farrMob[flowMob[0].Level].ToString());
            JArray usrMob = JArray.Parse(farrMob[0]["Assignees"]["UserId"].ToString());
            //推送显示文本
            var message = Db.GetIQueryable<PB_MobilizationNotice>().Where(p=>p.Id==Id).FirstOrDefault();
            string Title = message.ProjectName;
            var list = Db.GetIQueryable<PB_MobilzationItem>().Where(m=>m.ParentId==Id).ToList();
            foreach (var item in list) {
                Title += item.BuildingNo;
            }
            input.Str = $"进场通知:{Title} 请审批" + DateTime.Now.ToString("");
            string url = "eapp://pages/info/info?billid=" + Id + "&title=" + _objMob["StartState"]["Name"] + "&btn=" + _objMob["Action"]["Name"].ToString() + "&id=" + flowMob[0].Id + "";
            input.MessgUrl = url;
            //推送表单
            input.BillId = Id;
            //获取创建进场通知单创建者
            if (usrMob.Count > 0)
            {
                foreach (var u in usrMob)
                {
                    uids += "'" + u + "',";
                }
                var emps = await Db.GetListBySqlAsync<Base_User>("SELECT * FROM Base_User WHERE Id IN (" + uids.Substring(0, uids.Length - 1) + ")");
                foreach (var e in emps)
                {
                    ulist.Add(e.DingUserId);
                }
            }

            //推送用户集合
            input.ExecutorIds = ulist;
            //钉钉推送消息
            DingHelper.sendMessage(input);
        }

        /// <summary>
        /// 打印进场通知单
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<PB_MobilizationNoticePrint> MobilizationNoticePrint(string Id)
        {
            //获取要打印的主表信息
            var Data =await Db.GetIQueryable<PB_MobilizationNotice>().Where(x=>x.Id==Id).FirstOrDefaultAsync();
            PB_MobilizationNoticePrint DataFirst = new PB_MobilizationNoticePrint();
            DataFirst.Id = Data.Id;
            DataFirst.ProjectId = Data.ProjectId;
            DataFirst.SaleUnitId = Data.SaleUnitId;
            DataFirst.CooperativeUnitId = Data.CooperativeUnitId;
            DataFirst.SignUnitId = Data.SignUnitId;
            DataFirst.TypeId = Data.TypeId;
            DataFirst.ContractNo = Data.ContractNo;
            DataFirst.IssueDate = Data.IssueDate;
            DataFirst.AuditStatus = Data.AuditStatus;
            DataFirst.ProjectName = Data.ProjectName;
            DataFirst.SignUnitName = Data.SignUnitName;
            DataFirst.CooperativeUnitName = Data.CooperativeUnitName;
            DataFirst.SaleUnitName = Data.SaleUnitName;
            DataFirst.BusinessLeader = Data.BusinessLeader;
            DataFirst.DocumentaryContact = Data.DocumentaryContact;
            DataFirst.WorkFlow = Data.WorkFlow;
            var List =await Db.GetIQueryable<PB_MobilzationItem>().Where(m=>m.ParentId==Id&&m.BuildingnumberId!=null&&m.BuildingnumberId!="").ToListAsync();
            foreach (var ITEM in List) {
                var Datas = await Db.GetIQueryable<PB_Buildingnumber>().Where(x => x.Id == ITEM.BuildingnumberId).FirstOrDefaultAsync();
                if (!Datas.IsNullOrEmpty()) {
                    ITEM.BuildingNo = Datas.Buildingnumber;
                }
                        
               
            }
            DataFirst.SubData = List;
            return DataFirst;
        }

        #endregion

        #region 私有成员

        #endregion
    }
}